package gw.reportbuilder.util;

import java.sql.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class JDBCColumnUtil {

    public static List<String> getColumnValues(String tableName,
            String columnName, Connection conn) throws SQLException {

        List<String> result = new ArrayList<String>();
        PreparedStatement pstm;
        ResultSet rs;

        String sql = String.format("SELECT DISTINCT %s FROM %s WHERE %s IS NOT NULL ORDER BY %s ASC", columnName, tableName, columnName, columnName);

        pstm = conn.prepareStatement(sql);

        rs = pstm.executeQuery();

        while (rs.next()) {

            result.add(rs.getString(1));
        }

        return result;
    }
    
    public static String getColumnType(String tableName, String columnName, Connection conn) throws SQLException {
        
        String columnType = null;
        PreparedStatement pstm;
        ResultSet rs;

        String sql = String.format("SELECT %s FROM %s", columnName, tableName);

        pstm = conn.prepareStatement(sql);

        rs = pstm.executeQuery();

        if (rs.next()) {

            ResultSetMetaData rsmd = rs.getMetaData();

            int columnCount = rsmd.getColumnCount();

            for (int i = 1; i <= columnCount; i++) {

                columnType = rsmd.getColumnClassName(i);
            }
        }

        return columnType;
        
    }

    public static Map<String, String> getColumnMetadata(String tableName,
            Connection conn) throws SQLException {

        Map<String, String> columnTypeMap = new LinkedHashMap<String, String>();
        PreparedStatement pstm;
        ResultSet rs;

        String sql = String.format("SELECT * FROM %s", tableName);

        pstm = conn.prepareStatement(sql);

        rs = pstm.executeQuery();

        if (rs.next()) {

            ResultSetMetaData rsmd = rs.getMetaData();

            int columnCount = rsmd.getColumnCount();

            for (int i = 1; i <= columnCount; i++) {

                columnTypeMap.put(rsmd.getColumnName(i),
                        rsmd.getColumnClassName(i));
            }
        }

        return columnTypeMap;
    }
}
